package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"go-web/model"
	"io"
	"log"
	"math/rand"
	"os"
	"time"
)

var db *gorm.DB

func init() {
	conn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local&timeout=10s",
		"admin123",
		"Lingmaimai001",
		"mysql8.rwlb.rds.aliyuncs.com:3306",
		"test",
	)

	var err error
	if db, err = gorm.Open("mysql", conn); err != nil {
		log.Fatalf("Fail to connect db : %v", err)
	}

	//defer DB.Close()

	db.LogMode(true)
	//默认加s， grom转义struct名字的时候不用加上s
	//db.SingularTable(true)

	// idle 空闲的
	db.DB().SetMaxIdleConns(40)
	db.DB().SetMaxOpenConns(40)
}

func main() {

	rand.Seed(time.Now().UnixNano())

	gin.SetMode(gin.ReleaseMode)
	f, _ := os.Create("gin.log")
	gin.DefaultWriter = io.MultiWriter(f)

	r := gin.Default()
	r.GET("/order", func(c *gin.Context) {
		// 判断库存
		goodsId := 1
		var goods model.Goods
		db.Find( &goods, goodsId)
		if goods.Stock <= 0 {
			c.JSON(200, gin.H{
				"message": "sale out",
			})
			return
		}

		order(goodsId, 1)

		c.JSON(200, gin.H{
			"message": "sale",
		})
	})

	r.Run()
}

func order(goodsId int, number int) {
	tx := db.Begin()
	// 减库存
	var goods model.Goods
	rowsAffected := db.Model(&goods).Where("id = ?", goodsId).Where("stock - ? >= 0", number).UpdateColumn("stock", gorm.Expr("stock - ?", number)).RowsAffected
	if rowsAffected == 0 {
		tx.Rollback()
		return
	}

	// 下单
	var order = new(model.Order)
	order.UserId = rand.Intn(1000000)
	order.GoodsId = goodsId
	order.Number = number
	if err := tx.Create(order).Error; err != nil {
		tx.Rollback()
		return
	}
	tx.Commit()
}

